import logging
import os
from functools import lru_cache

__all__ = ['settings']

from dotenv import load_dotenv

from env_config.base_config import BaseConfig

logger = logging.getLogger(__name__)

# 加载 .env 文件中的环境变量
load_dotenv('./env')

env = os.getenv('ENV', 'dev')

logger.info(f'env: {env}')

config_mapping = {
    'dev': 'env_config.dev_config.DevConfig',
    'prod': 'env_config.prod_config.ProdConfig',
    'test': 'env_config.test_config.TestConfig',
}


@lru_cache()
def get_config() -> BaseConfig:
    """获取并缓存应用配置"""
    # 动态导入相应的配置类
    config_class_path = config_mapping.get(env, 'env_config.base_config.ProdConfig')
    module_name, class_name = config_class_path.rsplit('.', 1)
    config_class = getattr(__import__(module_name, fromlist=[class_name]), class_name)

    app_config: BaseConfig = config_class()
    return app_config


settings: BaseConfig = get_config()
